/**
 * 操作日志相关功能
 */
import db, { mysql } from 'src-ssr/db/connect';
import TableHelper from 'src-ssr/db/tableHelper';
import * as tools from 'src-ssr/util/common';
import autocode from 'src-ssr/util/autocode';
import shortid from 'shortid';
import md5 from 'md5';
import logs from 'src-ssr/util/logs';
import workflow from 'src-ssr/util/workflow';
import schedule from 'src-ssr/util/schedule';
import { Sequelize, Op, QueryTypes } from 'sequelize';
import models, { sequelize } from 'src-ssr/db/sequelize';
import mDict from 'src-ssr/util/dictionary';

// 操作日志
export const logsList = async (req, res) => {
  const { startRow, count, filter, sortBy, descending } = req.body;

  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);
  const where = { tenant_id: filter && filter.tenant_id || user.tid }, order = [];

  // 非管理员只能查看自己租户的日志
  if (user.tid > 0 && user.tid != where.tenant_id) {
    return res.json({
      data: [],
      rowsNumber: 0
    });
  }

  if (filter) {
    if (filter.create_time) {
      const time = filter.create_time.split('|');
      where.create_time = { [Op.gte]: time[0], [Op.lte]: time[1] };
    }
    if (filter.user_id) {
      where.user_id = filter.user_id;
    }
    if (filter.oper_type) {
      where.oper_type = filter.oper_type;
    }
    if (filter.oper_model) {
      where.oper_model = filter.oper_model;
    }
    if (filter.oper_content) {
      where.oper_content = { [Op.like]: `%${filter.oper_content.replace(/%|'/g, '')}%` }
    }
  }
  sortBy && order.push([sortBy, descending ? 'DESC' : 'ASC']);

  const ret = await models.t_operation_logs.findAndCountAll({
    attributes: {
      include: [
        [Sequelize.fn('CONCAT', Sequelize.col('ip'), Sequelize.col('geography')), 'ipgeo']
      ]
    },
    where,
    order,
    offset: startRow,
    limit: count,
    raw: true
  });

  res.json({
    data: ret.rows,
    rowsNumber: ret.count
  });
};

// 获取操作模块
export const getOperModel = async (req, res) => {
  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);

  const rows = await models.t_operation_logs.findAll({
    attributes: [[Sequelize.fn('DISTINCT', Sequelize.col('oper_model')), 'oper_model']],
    where: {
      oper_model: { [Op.ne]: '' },
      oper_type: { [Op.ne]: 'sync' },
      tenant_id: user.tid
    }
  });
  res.json(rows);
}

// 更新超期天数
export const updateLogsExpireDays = async (req, res) => {
  const { days } = req.body;
  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);

  if (days > 0) {
    await models.m_config.update({ value: { expireDays: days } }, { where: { key: 'logs', tenant_id: user.tid } });
    schedule.restart();
  }
  res.json({ result: 'ok' })
}
